<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-header">
        <el-icon class="logo-icon"><HomeFilled /></el-icon>
        <h1 class="system-title">脑卒中溶栓治疗平台</h1>
        <p class="subtitle">欢迎登录管理系统</p>
      </div>
      
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            :validate-event="false"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            :validate-event="false"
            show-password
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="remember" class="remember-checkbox">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-link type="primary" :underline="false" @click="showForgotPassword = true">忘记密码？</el-link>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="login-button" 
            :loading="loading" 
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
        
        <div class="register-link">
          <span>还没有账号？</span>
          <el-link type="primary" :underline="false" @click="goToRegister">立即注册</el-link>
        </div>
      </el-form>
      
      <!-- 系统信息 -->
      <div class="system-info">
        <p>脑卒中溶栓治疗大数据处理平台 v1.0.0</p>
      </div>
    </div>
    
    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="showForgotPassword"
      title="找回密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="forgotForm" :rules="forgotRules" ref="forgotFormRef">
        <el-form-item prop="email">
          <el-input
            v-model="forgotForm.email"
            placeholder="请输入注册邮箱"
            prefix-icon="Message"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" class="reset-password-button" @click="handleResetPassword">
            发送重置链接
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { HomeFilled } from '@element-plus/icons-vue'
import { userAPI } from '../api'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref(null)
const showForgotPassword = ref(false)
const forgotFormRef = ref(null)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 忘记密码表单
const forgotForm = reactive({
  email: ''
})

// 登录表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ]
}

// 忘记密码表单验证规则
const forgotRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  try {
    // 表单验证
    await loginFormRef.value.validate()
    loading.value = true
    
    // 调用登录API
    // 注意：这里使用模拟数据，实际应该调用真实API
    // const response = await userAPI.login(loginForm.username, loginForm.password)
    
    // 模拟登录成功
    setTimeout(() => {
      // 模拟用户数据
      const mockUser = {
        user_id: 1,
        user_name: loginForm.username,
        email: `${loginForm.username}@example.com`,
        role: loginForm.username === 'admin' ? 'admin' : 'user'
      }
      
      // 保存登录信息到localStorage
      localStorage.setItem('token', 'mock_token_' + Date.now())
      localStorage.setItem('userInfo', JSON.stringify(mockUser))
      localStorage.setItem('userRole', mockUser.role)
      localStorage.setItem('userName', mockUser.user_name)
      
      // 如果选择记住我，保存用户名到localStorage
      if (loginForm.remember) {
        localStorage.setItem('rememberedUsername', loginForm.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }
      
      ElMessage.success('登录成功')
      
      // 登录成功后直接跳转到用户中心页面
      router.push(`/stroke-profile/${mockUser.user_id}`)
      
    }, 1000)
    
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  try {
    await forgotFormRef.value.validate()
    
    // 这里应该调用重置密码API
    ElMessageBox.alert('重置密码链接已发送到您的邮箱，请查收。', '操作成功', {
      confirmButtonText: '确定',
      callback: () => {
        showForgotPassword.value = false
        forgotForm.email = ''
      }
    })
    
  } catch (error) {
    console.error('重置密码失败:', error)
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 页面加载时，检查是否有记住的用户名
const rememberedUsername = localStorage.getItem('rememberedUsername')
if (rememberedUsername) {
  loginForm.username = rememberedUsername
  loginForm.remember = true
}
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #FFFFFF;
  padding: 20px;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
  background: #FFFFFF;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

.system-title {
  font-size: 24px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 16px;
  color: #606266;
}

.login-form {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
  border-radius: 8px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
  box-shadow: none;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__inner) {
  color: #303133;
}

:deep(.el-input__placeholder) {
  color: #c0c4cc;
}

.remember-checkbox {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-checkbox__label) {
  color: #606266;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #409eff;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  border-radius: 8px;
  background-color: #409eff;
  border-color: #409eff;
}

.login-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.login-button.is-loading {
  background-color: #409eff;
  border-color: #409eff;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #606266;
}

.system-info {
  text-align: center;
  margin-top: 20px;
  color: #909399;
  font-size: 12px;
}

.reset-password-button {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-wrapper {
    padding: 25px;
  }
  
  .system-title {
    font-size: 20px;
  }
  
  .subtitle {
    font-size: 14px;
  }
  
  .logo-icon {
    font-size: 36px;
  }
}
</style>